﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using TouchSocket.Core.IO;
using TouchSocket.Core.Log;
using TouchSocket.Core.Run;
using Updater.Core;
namespace Updater.Server
{
    public static class Program
    {
        public static int UpdateCount = 0;
        static UPTcpService service;
        /// <summary>
        /// 密文
        /// </summary>
        public static string Token="";
        /// <summary>
        /// 指定是否可以通过客户端来更新
        /// </summary>
        public static bool IsClientUpdata=false;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string title = ConfigurationManager.AppSettings["Title"];
            int port = int.Parse(ConfigurationManager.AppSettings["Port"]);

            if (VersionHelper.PortInUse(port))
            {
                Console.WriteLine($"检测到{port}端口已经被占用，请通过config文件修改服务端口,按任意键退出");
                Console.ReadKey();
                System.Environment.Exit(0);
            }
            //1.先判断文件是否存在
            if (!File.Exists("UpdateConfiguration.xml"))
            {
               
                //不存在则新建一个文件
                UpdateConfiguration updateConfiguration = new UpdateConfiguration();
                updateConfiguration.Save("UpdateConfiguration.xml");
            }
            //指定可以通过客户端来更新
            IsClientUpdata = true;
            //指定密文
            Token = "123";
            //初始化服务类
            service = new UPTcpService(port);
            //注册服务
            service.RpcStore.RegisterServer<UpRpcServer>();
           // Console.WriteLine(service.ShareProxy(1235));
            Console.Title = title + $",服务类型：[TCP],[Port：{port}]";

            service.Message("服务器启动完成");



            ConsoleAction consoleAction = new ConsoleAction("h|help|?");//设置帮助命
            consoleAction.OnException += ConsoleAction_OnException;//订阅执行异常输出

            consoleAction.Add("sp|shareProxy", "分享代理", ShareProxy);//示例命令
            consoleAction.Add("ssp|stopShareProxy", "停止分享代理", StopShareProxy);//示例命令
            consoleAction.Add("udf|upDateFile", "更新本地文件", UpdateConfiguration);//示例命令
            consoleAction.Add("ex|exit", "退出服务器", Exit);

            consoleAction.Add("cl|clert", "清空控制台", Clear);
            FileLogger fileLogger = new FileLogger();
            while (true)
            {
                if (!consoleAction.Run(Console.ReadLine()))
                {
                    Console.WriteLine("命令不正确，请输入“h|help|?”获得帮助。");
                }
            }
           
        }

        private static void Clear()
        {
            Console.Clear();
        }

        private static void Exit()
        {
            service.Dispose();
            System.Environment.Exit(0);
        }

        private static void StopShareProxy()
        {
            service.RpcStore.StopShareProxy();
            Console.WriteLine("分享代理已停止");
        }

        private static void ShareProxy()
        {
            Console.WriteLine(service.ShareProxy(1235));
        }

        private static void ConsoleAction_OnException(Exception obj)
        {
            Console.WriteLine(obj.Message);
        }

        /// <summary>
        /// 检查文件更新
        /// </summary>
        public static void UpdateConfiguration()
        {
            service.Message("开始检查是否由文件更新");
            UpdateConfiguration config = FastJson.Load<UpdateConfiguration>("UpdateConfiguration.xml");
            List<string> files = FileHelper.GetOffspringFiles(AppDomain.CurrentDomain.BaseDirectory + "FileFolder\\");
            List<FileUnit> filesUnit = new List<FileUnit>();
            foreach (string filePath in files)
            {
                string filePathFull = AppDomain.CurrentDomain.BaseDirectory + "FileFolder\\" + filePath;
                FileInfo fileInfo = new FileInfo(filePathFull);
                filesUnit.Add(new FileUnit(filePath, 1, (int)fileInfo.Length, fileInfo.LastWriteTime));            
            }
            UpdateConfigInfo updateConfigInfo = FileHelper.GetUpdateConfigInfo(config, filesUnit);
            if (updateConfigInfo.Add.Count!=0)
            {
                foreach (FileUnit fileUnit in updateConfigInfo.Add)
                {
                    config.FileList.Add(fileUnit);
                }

            }
            if (updateConfigInfo.Delete.Count!=0)
            {
                foreach (FileUnit fileunit in updateConfigInfo.Delete)
                {
                    config.FileList.Remove(fileunit);
                }
            }
            if (updateConfigInfo.Change.Count!=0)
            {
                foreach (FileUnit fileunit in updateConfigInfo.Change)
                {
                    for (int i = 0; i < config.FileList.Count; i++)
                    {
                        if (config.FileList[i].FileRelativePath==fileunit.FileRelativePath)
                        {
                            config.FileList[i].Version++;
                            config.FileList[i].FileSize=fileunit.FileSize;
                            config.FileList[i].LastUpdateTime=fileunit.LastUpdateTime;
                            break;
                        }


                    }
                }
            }
            if (updateConfigInfo.Add.Count != 0|| updateConfigInfo.Delete.Count != 0|| updateConfigInfo.Change.Count != 0)
            {
                config.ClientVersion++;
                config.Save(AppDomain.CurrentDomain.BaseDirectory + "UpdateConfiguration.xml");
                service.Message($"更新：{updateConfigInfo.Add.Count}，新增：{updateConfigInfo.Change.Count}，删除：{updateConfigInfo.Delete.Count}最新版本号{config.ClientVersion}");
            }
            else
            {
                service.Message($"更新：{updateConfigInfo.Add.Count}，新增：{updateConfigInfo.Change.Count}，删除：{updateConfigInfo.Delete.Count}最新版本号{config.ClientVersion}");
            }


        }
        /// <summary>
        /// 给定文件列表来检查文件更新
        /// </summary>
        /// <param name="files"></param>
        public static void UpdateConfiguration(List<string> files)
        {
            service.Message("开始检查是否由文件更新，给定文件列表");
            UpdateConfiguration config = FastJson.Load<UpdateConfiguration>("UpdateConfiguration.xml");
           
            List<FileUnit> filesUnit = new List<FileUnit>();
            foreach (string filePath in files)
            {
                FileInfo fileInfo = new FileInfo(filePath);
                filesUnit.Add(new FileUnit(filePath, 1, (int)fileInfo.Length, fileInfo.LastWriteTime));
            }
            UpdateConfigInfo updateConfigInfo = FileHelper.GetUpdateConfigInfo(config, filesUnit);
            if (updateConfigInfo.Add.Count != 0)
            {
                foreach (FileUnit fileUnit in updateConfigInfo.Add)
                {
                    config.FileList.Add(fileUnit);
                }

            }
            if (updateConfigInfo.Delete.Count != 0)
            {
                foreach (FileUnit fileunit in updateConfigInfo.Delete)
                {
                    config.FileList.Remove(fileunit);
                }
            }
            if (updateConfigInfo.Change.Count != 0)
            {
                foreach (FileUnit fileunit in updateConfigInfo.Change)
                {
                    for (int i = 0; i < config.FileList.Count; i++)
                    {
                        if (config.FileList[i].FileRelativePath == fileunit.FileRelativePath)
                        {
                            config.FileList[i].Version++;
                            config.FileList[i].FileSize = fileunit.FileSize;
                            config.FileList[i].LastUpdateTime = fileunit.LastUpdateTime;
                            break;
                        }


                    }
                }
            }
            if (updateConfigInfo.Add.Count != 0 || updateConfigInfo.Delete.Count != 0 || updateConfigInfo.Change.Count != 0)
            {
                config.ClientVersion++;
                config.Save(AppDomain.CurrentDomain.BaseDirectory + "UpdateConfiguration.xml");
                service.Message($"更新：{updateConfigInfo.Add.Count}，新增：{updateConfigInfo.Change.Count}，删除：{updateConfigInfo.Delete.Count}最新版本号{config.ClientVersion}");
            }


        }

    }
}
